<?php


namespace common\helpers\Uploads;


use common\helpers\commonApi;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云oss存储安装 composer require aliyuncs/oss-sdk-php
 * Class AlyOssApi
 * @package common\helpers\Uploads
 */
class AlyOssApi implements Upload
{
    private $ossClient = null;
    private $accessKeyId = null;
    private $accessKeySecret = null;
    private $endpoint = null;
    private $bucket = null;

    public function __construct($accessKeyId, $accessKeySecret, $endpoint, $bucket)
    {
        $this->accessKeyId = $accessKeyId;//获取阿里云oss的accessKeyId
        $this->accessKeySecret = $accessKeySecret;//获取阿里云oss的accessKeySecret
        $this->endpoint = $endpoint;
        $this->bucket = $bucket;//获取阿里云oss的endPoint
        if (!$this->ossClient){
            try{
                $this->ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            } catch(OssException $e) {
                return commonApi::message($e->getMessage(),false);
            }
        }
    }

    public function uploadFile(string $filePath, string $fileName)
    {
        $this->ossClient->uploadFile($this->bucket, $fileName, $filePath);
        return commonApi::message();
    }

    public function delete(string $filePath)
    {
        $this->ossClient->deleteObject($this->bucket, $filePath);
        return commonApi::message();
    }

    public function deleteAll(array $filePaths)
    {
        $success = 0;
        $fail = 0;
        $fail_data = [];
        $success_data = [];
        foreach ($filePaths as $filePath){
            $res = $this->delete($filePath);
            if ($res['success']){
                $success += 1;
                $success_data[] = $filePath;
            }else{
                $fail += 1;
                $fail_data[] = $filePath;
            }
        }
        return commonApi::message("删除失败：成功{$success}条，失败{$fail}条", true, ['success' => $success_data, 'fail' => $success_data]);
    }
}